package org.ponly.lpf4j.web;

import org.ponly.lpf4j.PluginManager;
import org.ponly.web.servlet.ProxiedFilterChain;

import javax.servlet.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 */
class PluginFilter implements Filter {
    private PluginManager pluginManager;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Filter[] filters = pluginManager.getExtensions(Filter.class);
        ServletMapping[] mappings = pluginManager.getExtensions(ServletMapping.class);
        ServletDispatcher dispatcher = new ServletDispatcher(mappings);

        List<Filter> pluginFilters = new ArrayList<>();
        pluginFilters.addAll(Arrays.asList(filters));
        pluginFilters.add(dispatcher);

        new ProxiedFilterChain(filterChain, pluginFilters).doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
